package com.zuxia.service.imp;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zuxia.config.MyAliPayConfig;
import com.zuxia.exception.ZuxiaBusinessException;
import com.zuxia.payment.PayOpenFeginApi;
import com.zuxia.service.PayService;
import com.zuxia.utils.RedisUtils;
import com.zuxia.utils.ResultCodeEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.alipay.api.AlipayConstants.*;
import static io.swagger.models.properties.LongProperty.FORMAT;
import static org.apache.catalina.manager.Constants.CHARSET;

/**
 * @className: PayServiceImp
 * @Description: TODO
 * @version: v1.８.0
 * @author: Liuxin-G
 * @date: 2024/11/13 9:18
 */
@Service
public class PayServiceImp implements PayService {

    @Resource
    private RedisUtils redisUtils;
    @Resource
    private MyAliPayConfig myAliPayConfig;
    @Resource
    private AlipayClient alipayClient;

    @Override
    public String payment(String orderId,Float price) throws Exception {
            try {
                //开启支付流程
                String result = "";
                AlipayTradePagePayRequest request = getAlipayTradePagePayRequest(orderId, price);
                AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
                if(response.isSuccess()){
                    result = response.getBody();
                    System.out.println(result);
                    redisUtils.setString(redisUtils.getZFB_URL_Key()+orderId,result);
                    return result;
                } else {
                    throw new ZuxiaBusinessException(ResultCodeEnum.ORDERS_EROEE);
                }

            }catch (Exception e){
                throw new ZuxiaBusinessException(ResultCodeEnum.ORDERS_EROEE);
            }
    }

    private AlipayTradePagePayRequest getAlipayTradePagePayRequest(String orderId, Float price) {
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(myAliPayConfig.getNotifyUrl());
        request.setReturnUrl(myAliPayConfig.getReturnUrl());
        com.alibaba.fastjson.JSONObject bizContent = new com.alibaba.fastjson.JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", orderId);
        bizContent.put("timeout_express","10m");
        //支付金额，最小值0.01元
        bizContent.put("total_amount", price);
        //订单标题，不可使用特殊符号
        bizContent.put("subject", "商品订单");
        //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toString());
        return request;
    }

    // 订单取消退款
    @Override
    public boolean refund(String orderId,Float money) {
        //退款
        AlipayClient alipayClient = new DefaultAlipayClient(
                myAliPayConfig.getServerUrl(),
                myAliPayConfig.getAppid(),
                myAliPayConfig.getPrivateKey(),
                FORMAT, CHARSET,
                myAliPayConfig.getAlipayPublicKey(),
                SIGN_TYPE_RSA);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        LambdaQueryWrapper lqw = new LambdaQueryWrapper();
        // 根据订单id查询订单信息
        lqw.eq(APP_ID, orderId);
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", orderId);
        bizContent.put("refund amount",money);
        bizContent.put("out_request_no","HZ01RF001");
        bizContent.put("body",money!=null?"支付超时":"订单取消");
        request.setBizContent(bizContent.toString());
        try {
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                System.out.println("退款成功");
                return true;
            } else {
                System.out.println("退款失败");
                return false;
            }
        } catch (Exception e) {
            System.out.println("退款失败");
            e.printStackTrace();
            return false;

        }
    }
}